import {
  createStore
} from 'vuex'
import websdk from "easemob-websdk"
import config from "../utils/WebIMConfig";
import {saveChatRecord} from "../api/user"


import {
  Notify
} from 'vant';
export default createStore({
  state: {
    WebIM: {},
    conn: {},
 

    currentUserId: '', //对话者id
    //对话列表
    userList: [
          
    ],
    //对话者聊天记录
    chatRecord: [

    ]

  },
  mutations: {
    //创建连接
    initWebIM: function (state, payload) {

      state.WebIM = websdk;
      state.WebIM.config = config;
      state.conn = state.WebIM.conn = new WebIM.connection({
        appKey: WebIM.config.appkey,
        isHttpDNS: WebIM.config.isHttpDNS,
        isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
        https: WebIM.config.https,
        url: WebIM.config.socketServer,
        apiUrl: WebIM.config.restServer,
        isAutoLogin: WebIM.config.isAutoLogin,
        autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
        autoReconnectInterval: WebIM.config.autoReconnectInterval,
        delivery: WebIM.config.delivery,
        useOwnUploadFun: WebIM.config.useOwnUploadFun
      })

      state.conn.listen({
        onOpened: function (message) {}, //连接成功回调 
        onClosed: function (message) {}, //连接关闭回调
        onTextMessage: function (message) {}, //收到文本消息
        onEmojiMessage: function (message) {}, //收到表情消息
        onPictureMessage: function (message) {}, //收到图片消息
        onCmdMessage: function (message) {}, //收到命令消息
        onAudioMessage: function (message) {}, //收到音频消息
        onLocationMessage: function (message) {}, //收到位置消息
        onFileMessage: function (message) {}, //收到文件消息
        onVideoMessage: function (message) {
          var node = document.getElementById('privateVideo');
          var option = {
            url: message.url,
            headers: {
              'Accept': 'audio/mp4'
            },
            onFileDownloadComplete: function (response) {
              var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
              node.src = objectURL;
            },
            onFileDownloadError: function () {
              console.log('File down load error.')
            }
          };
          WebIM.utils.download.call(conn, option);
        }, //收到视频消息
        onPresence: function (message) {}, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
        onRoster: function (message) {}, //处理好友申请
        onInviteMessage: function (message) {}, //处理群组邀请
        onOnline: function () {}, //本机网络连接成功
        onOffline: function () {}, //本机网络掉线
        onError: function (message) {}, //失败回调
        onBlacklistUpdate: function (list) { //黑名单变动
          // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
          console.log(list);
        },
        onRecallMessage: function (message) {}, //收到撤回消息回调
        onReceivedMessage: function (message) {}, //收到消息送达服务器回执
        onDeliveredMessage: function (message) {}, //收到消息送达客户端回执
        onReadMessage: function (message) {}, //收到消息已读回执
        onCreateGroup: function (message) {}, //创建群组成功回执（需调用createGroupNew）
        onMutedMessage: function (message) {} //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
      });

      let options = {
        apiUrl: WebIM.config.apiURL,
        user: payload.userName,
        pwd: payload.passWord,
        appKey: state.WebIM.config.appkey,
        success: function (res) {
          console.log(res)
          console.log('成功')
        },
        error: function (err) {
          console.log(err)
        }
      };


      state.conn.open(options);
      state.conn.listen({
        onOpened: function (message) { //连接成功回调 
          console.log('登录成功')
        },
        onTextMessage: function (msg) {

          if ('hx'+state.currentUserId !== msg.from) {
            Notify({
              type: 'success',
              message: "收到" + msg.from + "的消息" + msg.data
            });
          }
          //收到文本消息
      
          console.log(msg)

          if (msg.from =="hx"+ state.currentUserId) {
            state.chatRecord.push(msg)
          }
        }
      })
    },
    //关闭连接
    closeWebIM: function (state) {
      state.conn.close()
    },
    //发送消息
    sendMessage: function (state, payload) {
      console.log(payload);
      let id = state.conn.getUniqueId(); // 生成本地消息id
      let msg = new WebIM.message('txt', id); // 创建文本消息
      msg.set({
        msg: payload.msgContent, // 消息内容
        to: payload.to, // 接收消息对象（用户id）
        chatType: 'singleChat', // 设置为单聊
        ext: {
          isImage: payload.isImage,
          url: payload.imgUrl
        }, //扩展消息
        success: function (id, serverMsgId) {
          console.log('send private text Success');
        },
        fail: function (e) {
          // 失败原因:
          // e.type === '603' 被禁言
          // e.type === '605' 群组不存在
          // e.type === '602' 不在群组或聊天室中
          // e.type === '504' 撤回消息时超出撤回时间
          // e.type === '505' 未开通消息撤回
          // e.type === '506' 没有在群组或聊天室白名单
          // e.type === '503' 未知错误
          console.log("Send private text error");
        }
      });

      state.conn.send(msg.body);
      msg.body.sourceMsg = payload.msgContent
      msg.body.from = payload.from
      state.chatRecord.push(msg.body)
     
      // let ext =msg.body.ext
      // msg.body.ext=JSON.stringify(ext)
  
      saveChatRecord(msg.body)
    
    },
    //当前对话用户
    setCurrentUserId: function (state, id) {
      state.currentUserId = state.userList[id].docId
      console.log('进入与' + state.userList[id].docId + "聊天页面")
    },
    //获取用户好友列表
    getUserList:function(state,payload){

      state.userList=[]
      state.userList.push(JSON.parse(payload)[0])   
    },
    //获取聊天记录
    getRecords: function (state, payload) {
      state.chatRecord = payload.records
    }


  },
  actions: {},
  modules: {}
})